package com.MSofLectures.Tool;

import java.io.Serializable;

import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class DatabaseControler {
	/*
	 * @author ufo
	 * 这个类实现数据库读写，在hibernate和应用之间加了一层，这一层将实现一些频繁读取的数据放到内存当中
	 * 
	 */
	private SessionFactory sf;
	public Session hibernateSess=null;
	public Transaction tx = null;

	public DatabaseControler(SessionFactory sf){
		this.setSf(sf);
		this.hibernateSess=this.getSf().openSession();
		this.hibernateSess.setFlushMode(FlushMode.AUTO);//待测试，如果遇到极其繁忙的情况可以设置成ALWAYS
		//AUTO在每次调用当中，只要发现脏数据，就会进行同步
		this.tx=this.hibernateSess.beginTransaction();
	}
	public  Serializable save(Object target){
		return hibernateSess.save(target);
	}
	public void commit(){
		this.tx.commit();
		this.hibernateSess.close();
		this.hibernateSess=this.getSf().openSession();
		this.tx = this.hibernateSess.beginTransaction();
	}
	public Object load(Class<?> arg0, Serializable arg1){
		return this.hibernateSess.load(arg0, arg1);
	}
	public void delete(Object target){
		this.hibernateSess.delete(target);
	}
	public void finalize() throws Throwable{
		this.tx.commit();
		this.hibernateSess.close();
		super.finalize();
	}
	public SessionFactory getSf() {
		return this.sf;
	}
	public void setSf(SessionFactory sf) {
		this.sf = sf;
	}
}
